<script setup lang="ts">
import { selectPipePoint, clearBurstAnalysis, burstAnalysis } from '@/utils/burstAnalysis'
import { useToolboxStore } from '@/stores'

const toolboxStore = useToolboxStore()
const isExpanded = ref(false)
const toolboxId = 'toolbox-burstAnalysis'

const handleClickOutside = (event: MouseEvent) => {
  const toolContainer = document.querySelector('.burst-container')
  if (toolContainer && !toolContainer.contains(event.target as Node) && isExpanded.value) isExpanded.value = false
}

onMounted(() => document.addEventListener('click', handleClickOutside))

onBeforeUnmount(() => document.removeEventListener('click', handleClickOutside))

watch(
  () => toolboxStore.expandedToolboxId,
  (newId) => (isExpanded.value = newId === toolboxId)
)

const toggleExpand = () => {
  if (isExpanded.value) {
    toolboxStore.setExpandedToolboxId('')
  } else {
    toolboxStore.setExpandedToolboxId(toolboxId)
  }
  isExpanded.value = !isExpanded.value
}

function select() {
  selectPipePoint()
}

function start() {
  burstAnalysis()
}

function clear() {
  clearBurstAnalysis()
}
</script>

<template>
  <div class="burst-container">
    <div class="burst-row" @click.stop="toggleExpand">
      <img src="@/assets/svgs/burst.svg" alt="爆管分析" />
      <span>爆管分析</span>
      <img src="@/assets/svgs/up.svg" alt="上" v-if="isExpanded" />
      <img src="@/assets/svgs/down.svg" alt="下" v-else />
    </div>
    <transition name="fade">
      <div v-if="isExpanded">
        <div class="burst-row" @click="select">
          <img src="@/assets/svgs/select.svg" alt="选择爆管点" />
          <span>选择爆管点</span>
        </div>
        <div class="burst-row" @click="start">
          <img src="@/assets/svgs/find.svg" alt="开始分析" />
          <span>开始分析</span>
        </div>
        <div class="burst-row" @click="clear">
          <img src="@/assets/svgs/clear.svg" alt="清除" />
          <span>清除</span>
        </div>
      </div>
    </transition>
  </div>
</template>

<style lang="scss" scoped>
.burst-container {
  position: absolute;
  top: 55px;
  width: 95px;
  height: auto;
  left: 350px;
  background-color: #0a1831a0;
  border-radius: 4px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;

  .burst-row {
    display: flex;
    align-items: center;
    color: #ccc;
    cursor: pointer;
    padding: 5px 0;

    img {
      width: 20px;
      height: 15px;
      margin-right: 2px;
    }

    span {
      font-size: 12px;
    }
  }
}
</style>
